#!/bin/bash

#set -x

gen_proto() {
  rm -rf /tmp/protos
  mkdir -p /tmp/protos
  googleapis=`echo $GOPATH/pkg/mod/github.com/grpc-ecosystem/grpc-gateway@*/third_party/googleapis`

  for f in $(find . -name "*.proto") ; do
    echo "gen proto File -> $f";
    echo "protoc -Isrc -I/usr/local/include -I$GOPATH/src \
    -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway \
    -I$googleapis \
    --go_out=plugins=grpc:/tmp/protos \
    --govalidators_out=/tmp/protos \
    --grpc-gateway_out=logtostderr=true:/tmp/protos $f"
    protoc -Isrc -I/usr/local/include -I$GOPATH/src \
    -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway \
    -I$googleapis \
    --go_out=plugins=grpc:/tmp/protos \
    --govalidators_out=/tmp/protos \
    --grpc-gateway_out=logtostderr=true:/tmp/protos $f
  done ;

  cp -rf /tmp/protos/gitee.com/wushc/demo-protos/goout .
}

gen_mock() {
  for f in $(find ./goout/ -name "*.pb.go") ; do
    services=$(cat $f |grep interface|grep -o "[A-Z].*Client")
    dirname=$(basename $(dirname $f));
    savedirname="mock_${dirname}";
    savefilename="mock_${dirname}.go";
    if  [ $services ]; then
      echo "gen mock File -> $f";
      mockgen -destination=gooutmock/$savedirname/$savefilename  gitee.com/wushc/demo-protos/goout/$dirname $services;
    fi;
  done ;
}

if [ "all" == "$2" ]; then
  gen_all $1
else
  gen_$1
fi;